package cloud.lysky.java.on.concurrent.cas;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

/**
 * @author luoly
 * @describe
 * @date 2022-10-21 22:36
 **/

public class ABATest {

    public static void main(String[] args) {
        //AtomicInteger:AtomicInteger类是系统底层保护的int类型，通过提供执行方法的控制进
        //行值的原子操作,它有比较和交换的操作方法
        AtomicInteger atomicInteger = new AtomicInteger(1);

        //开启一个线程
        new Thread(() -> {
            int value = atomicInteger.get();
            System.out.println("线程1读到的value值：" + value);
            //阻塞1秒
            LockSupport.parkNanos(1000000000L);
            //线程1通过CAS修改Value值为3
            if (atomicInteger.compareAndSet(value,3)){
                System.out.println("线程1将value的值从" + value + "更新为3");
            }else{
                System.out.println("线程1更新失败！");
            }
        },"线程1").start();

        //开启第二个线程将值改成2再改回1
        new Thread(()->{
            int value = atomicInteger.get();
            System.out.println("线程2读到的value值：" + value);
            //修改value的值为2
            if (atomicInteger.compareAndSet(value,2)){
                System.out.println("线程2将value的值从" + value + "更新为2");
            }

            value = atomicInteger.get();
            System.out.println("线程2读到的value值：" + value);
            //再修改value的值为改回1
            if (atomicInteger.compareAndSet(value,1)){
                System.out.println("线程2将value的值从" + value + "更新为1");
            }
        },"线程2").start();
    }
    //Thread1不清楚Thread2对value的操作，误以为value=1没有修改过
}